<template>
  <div class="body">
    <div class="login" align="center">
      <div class="login-title">
        <h4>登录</h4>
      </div>
      <Form :model="form" class="form" :rules="rules" ref="form">
        <Form-item prop="username">
          <Input v-model="form.username" placeholder="请输入用户名" size="large">
            <Icon type="ios-person-outline" slot="prepend" size="22"></Icon>
          </Input>
        </Form-item>
        <Form-item prop="password">
          <Input v-model="form.password" placeholder="请输入密码" size="large" type="password" @keyup.enter.native="submit">
            <Icon type="ios-lock-outline" slot="prepend" size="22"></Icon>
          </Input>
        </Form-item>
        <Form-item>
          <Button type="primary" @click="submit">登录</Button>
        </Form-item>
      </Form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/login'

export default {
  name: 'Login',
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, type: 'string', message: '用户不能为空', trigger: 'blur' },
          { min: 3, max: 30, message: '用户名长度在3-30位之间', trigger: 'blur' },
          { pattern: /^[0-9A-Za-z_]{3,30}$/, message: '用户名只能包含数字、字母、下划线', trigger: 'blur' }
        ],
        password: [
          { required: true, type: 'string', message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 30, message: '密码长度在6-30位之间', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,30}$/, message: '密码只能包含数字、字母、特殊字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate((v) => {
        if (v) {
          login(this.form).then(res => {
            if (res.code === 200) {
              this.$Message.success(res.msg)
              sessionStorage.setItem('token', res.data.token)
              this.$router.push('/index')
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.body {
  width: 100%;
  height: 100%;
  background: url("../assets/bg.jpg") no-repeat center top;
}
.login {
  width: 400px;
  height: 280px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  .login-title {
    font-size: 26px;
    margin-top: 20px;
    color: aliceblue;
  }
  .form {
    margin: 30px;
  }
}
</style>
